﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace IFTRUE.BLL.OperationsDBSrv
{
    public class ServerProcess
    {
        /// <summary>
        ///  拼接并执行创建服务的命令
        /// </summary>
        /// <param name="sMGDBPath">MongoDB安装目录</param>
        /// <param name="sDBPath">数据库保存路径</param>
        /// <param name="sServerName">服务名称</param>
        /// <param name="iPort">端口号</param>
        /// <param name="sOutFileName">输出信息存放的文件名称</param>
        public void RunCreateServerCmd(string sMGDBPath, string sDBPath, string sServerName, string iPort, string sOutFileName)
        {
            string sLogPath = sDBPath + "\\log";
            if (!Directory.Exists(sLogPath))
            {
                Directory.CreateDirectory(sLogPath);//如不存在日志文件夹，则创建文件夹
            }
            sLogPath += "\\log.log";
            string sdbPath = sDBPath + "\\db";
            if (!Directory.Exists(sdbPath))
            {
                Directory.CreateDirectory(sdbPath);//如不存在数据库文件夹，则创建文件夹
            }            
            string[] spath = sDBPath.Split(':');
            StringBuilder sRunCreate = new StringBuilder();
            sRunCreate.Append(spath[0] + ":\r\n");
            sRunCreate.Append("cd " + sMGDBPath + "\r\n");
            sRunCreate.Append("mongod --install");
            sRunCreate.Append(" --serviceName " + sServerName);
            sRunCreate.Append(" --logpath " + sLogPath);
            sRunCreate.Append(" --dbpath " + sdbPath);
            sRunCreate.Append(" --port " + iPort.ToString());
            sRunCreate.Append(">" + sOutFileName + ".txt \r\n");
            sRunCreate.Append("net start " + sServerName + " \r\n");
            //执行命令
            RunCommand(sRunCreate.ToString());            
        }

        /// <summary>
        /// 执行控制台命令
        /// </summary>
        /// <param name="sCommand"></param>
        private void RunCommand(string sCommand)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(sCommand);
            p.StandardInput.WriteLine("exit");
            System.Threading.Thread.Sleep(2000);
        }
    }
}
